<template>
  <div class="login-body">
    <div class="bg"></div>
    <div class="login-panel">
    <el-form
     class="login-register"
    :model="formData"
    :rules="rules"
    ref="formDataRef"
    @submit.prevent
    >
      <div class="login-title">XCloud云盘</div>
    <!--input输入 -->
      <el-form-item prop="email">
        <el-input
        clearable
        placeholder="请输入邮箱"
        v-model.trim="formData.email"
        size="large"
        maxlength="150px"
        >
          <template #prefix>
            <span class="iconfont icon-account"></span>
          </template>
        </el-input>
      </el-form-item>
      <!--获取邮箱验证码 -->
      <el-form-item v-if="opType==0||opType==2">
        <div class="send-email-panel">
          <el-input
              clearable
              placeholder="请输入邮箱验证码"
              size="large"
              maxlength="150px"
              v-model.trim="formData.emailCode"
          >
            <template #prefix>
              <span class="iconfont icon-checkcode"></span>
            </template>
          </el-input>
          <el-button class="send-mail-btn" type="primary"
                     size="large" @click="getEmailCode"
          >
            获取邮箱验证码
          </el-button>
        </div>
        <el-popover placement="left-end" :width="500" trigger="click">
          <div>
            <p>1,在垃圾箱中查找邮箱验证码</p>
            <p>2,在邮箱中 头像->设置->反垃圾->白名单->设置邮件地址白名单</p>
            <p>3,将邮箱【2370881903@qq.com】添加到白名单不知道怎么设置？</p>
          </div>
          <template #reference>
            <span class="a-link" :style="{'font-size':'12px'}">未收到邮箱验证码?</span>
          </template>
        </el-popover>
      </el-form-item>
      <!-- 昵称 -->
      <el-form-item prop="nickName" v-if="opType==0">
        <el-input
            clearable
            size="large"
            placeholder="请输入昵称"
            v-model.trim="formData.nickName"
        >
          <template #prefix>
            <span class="iconfont icon-account"></span>
          </template>
        </el-input>
      </el-form-item>

      <!-- 登录密码 -->
      <el-form-item prop="password" v-if="opType==1">
        <el-input
            type="password"
            size="large"
            placeholder="请输入密码"
            v-model="formData.password"
            show-password
        >
          <template #prefix>
            <span class="iconfont icon-password"></span>
          </template>
        </el-input>
      </el-form-item>
      <!-- 注册密码 -->
      <el-form-item prop="RegisterPassword"  v-if="opType==2||opType==0">
        <el-input
        type="password"
        size="large"
        placeholder="请输入密码"
        v-model="formData.RegisterPassword"
        show-password
        >
          <template #prefix>
            <span class="iconfont icon-password"></span>
          </template>
        </el-input>
      </el-form-item>
      <!-- 确认密码 -->
      <el-form-item prop="ConfirmPassword" v-if="opType==2||opType==0">
        <el-input
            type="password"
            size="large"
            placeholder="请再次输入密码"
            v-model="formData.ConfirmPassword"
            show-password
        >
          <template #prefix>
            <span class="iconfont icon-password"></span>
          </template>
        </el-input>
      </el-form-item>
    <!--验证码      -->
      <el-form-item prop="checkCode" >
        <div class="check-code-panel">
          <el-input
              size="large"
              placeholder="请输入验证码"
              v-model="formData.checkCode"
              @keyup.enter="doSubmit"
          >
            <template #prefix>
              <span class="iconfont icon-checkcode"></span>
            </template>
          </el-input>
          <img :src="checkCodeUrl" class="check-code" @click="changeCheckCode(0)"/>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="remenberme-panel">
          <el-checkbox v-model="formData.remenberMe" size="default">记住我</el-checkbox>
        </div>
        <div class="no-account" v-if="opType==1">
          <a href="javascript:void(0)" class="a-link" @click="showPanel(2)" style="font-size: 14px">忘记密码?</a>
          <a href="javascript:void(0)" class="a-link" @click="showPanel(0)" style="font-size: 14px">没有账号?去注册</a>
        </div>
        <div class="no-account" v-if="opType==0">
          <a href="javascript:void(0)" class="a-link" @click="showPanel(1)" style="color: blue ;font-size: 14px">已有账号?去登录</a>
        </div>
        <div class="no-account" v-if="opType==2">
          <a href="javascript:void(0)" class="a-link" @click="showPanel(1)" style="color: blue ;font-size: 14px">去登录？</a>
        </div>
      </el-form-item>
    <!--  登录    -->
      <el-form-item>
        <el-button type="primary" class="op-btn" size="large" v-if="opType==1" @click="doSubmit">登录</el-button>
        <el-button type="primary" class="op-btn" size="large" v-if="opType==0" @click="doSubmit">注册</el-button>
        <el-button type="primary" class="op-btn" size="large" v-if="opType==2" @click="doSubmit">重置密码</el-button>
      </el-form-item>
      <el-popover placement="left-end" :width="500" trigger="click">
        <div>QQ登录接口开发中....</div>
        <template #reference>
          <div class="login-btn-qq" v-if="opType==1">
            快捷登录 <img class="img" src="@/assets/qq.jpg"/>
          </div>
        </template>
      </el-popover>
    </el-form>;
    </div>
    <Dialog
        :show="dialogConfig4SendMailCode.show"
        :title="dialogConfig4SendMailCode.title"
        :buttons="dialogConfig4SendMailCode.buttons"
        width="500px"
        :showCancel="false"
        @close="dialogConfig4SendMailCode.show=false"
    >
      <el-form
          :model="formData4SendMailCode"
          :rules="rules"
          ref="formData4SendMailCodeRef"
          @submit.prevent
      >
        <!--input输入 -->
        <el-form-item label="邮箱" size="large">
            {{formData.email}}
        </el-form-item>
        <el-form-item label="验证码" prop="checkCode">
         <div class="check-code-panel">
           <el-input
               clearable
               placeholder="请输入验证码"
               v-model.trim="formData4SendMailCode.checkCode"
               size="large"
           >
           </el-input>
           <img :src="checkCodeUrl4SendMailCode"
                class="check-code"
                @click="changeCheckCode(1)"/>
         </div>
        </el-form-item>
        </el-form>
    </Dialog>
  </div>
</template>


<script setup>
import {getCurrentInstance, nextTick, reactive, ref ,onMounted} from "vue";
import Dialog from "@/components/Dialog.vue";
import {useRouter,useRoute} from "vue-router";
import md5 from "js-md5"

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

/*操作类型 0:注册 1:登录 2:忘记密码*/
const opType = ref(1);
const showPanel = (type) =>{
  opType.value = type;
  restForm();
}
const ConfirmPassword = (rule,value,callback)=>{
  if (value!==formData.value.RegisterPassword){
      callback(new Error(rule.message));
  }else {
    callback();
  }
}

const formData = ref({});
const formDataRef = ref();
const rules = {
  email: [
    {required:true,message:"请输入邮箱"},
    {validator:proxy.Verify.email,message: "请输入正确的邮箱"}
  ],
  RegisterPassword: [
    {required:true,message:"请输入密码"},
    {validator:proxy.Verify.password,message: "密码必须包含字母、数字，且长度至少8位"}
  ],
  password:[
    {required:true,message:"请输入密码"},
    {validator:proxy.Verify.password,message: "密码必须包含字母、数字，且长度至少8位"}
  ],
  nickName: [
    {required:true,message:"请输入昵称"},
  ],
  ConfirmPassword: [
    {required:true,message:"请再次输入密码"},
    {validator:ConfirmPassword,message: "两次输入密码不一致"}
  ],
  checkCode: [
    {required:true,message:"请输入图片验证码"},
  ],
  remenberMe:[],
}

const api = {
  Register:"/register",
  checkCode:"/api/checkCode",
  sendEmailCode:"/sendEmailCode",
  login:"/login",
  resetPassword:"/resetPassword"
}
//获取验证码
const checkCodeUrl = ref(api.checkCode);
const checkCodeUrl4SendMailCode = ref(api.checkCode);

const changeCheckCode = (type) => {
  if (type==0){
    checkCodeUrl.value =
        api.checkCode + "?type=" +type + "&time=" +new Date().getTime();
  }else {
    checkCodeUrl4SendMailCode.value =
        api.checkCode + "?type=" +type + "&time=" +new Date().getTime();
  }
}

const formData4SendMailCode = ref({});
const formData4SendMailCodeRef = ref();

const dialogConfig4SendMailCode = reactive({
  show: false,
  title: "发送邮箱验证码",
  buttons: [
    {
      type:"primary",
      text:"发送验证码",
      click:(e)=>{
        sendEmailCode();
      },
    },
  ],
});
//发送邮箱验证码
const sendEmailCode=()=>{
  formData4SendMailCodeRef.value.validate(async (valid)=>{
    if (!valid){
      return;
    }
    const params = Object.assign({},formData4SendMailCode.value);
    params.type = opType.value == 0?0:1;
    let result = await proxy.Request({
      url:api.sendEmailCode,
      params:params,
      errorCallback:()=>{
        changeCheckCode(1)
      }
    })
    if (!result){
      return
    }
    proxy.Message.success("验证码发送成功,请登录邮箱查看!")
    dialogConfig4SendMailCode.show = false;
  })
}
const getEmailCode= ()=>{
  formDataRef.value.validateField("email", (valid) => {
    if (!valid){
      return;
    }
    dialogConfig4SendMailCode.show=true;
    nextTick(()=>{
      changeCheckCode(1);
      formData4SendMailCodeRef.value.resetFields();
      formData4SendMailCode.value={
        email:formData.value.email
      }
    })
  });
}
const doSubmit=()=>{
  formDataRef.value.validate(async (valid)=>{
    if(!valid){
      return;
    }
    let params = {};
    Object.assign(params,formData.value);
    //注册 找回密码
    if (opType.value==0||opType.value==2){
      params.password = params.RegisterPassword;
      delete params.RegisterPassword;
      delete params.ConfirmPassword;
    }else if (opType.value==1){
      let cookieLoginInfo = proxy.Cookies.get("loginInfo");
      let cookiePassword = cookieLoginInfo==null?null:cookieLoginInfo.password
      if (params.password!==cookiePassword){
        params.password = md5(params.password);
      }
    }
    let url = null;
    if (opType.value==0){
      url = api.Register
    }
    if (opType.value==1){
      url = api.login
    }
    if (opType.value==2){
      url = api.resetPassword
    }
    let result = await proxy.Request({
      url:url,
      params:params,
      errorCallback:()=>{
        changeCheckCode(0)
      }
    })
    if (!result){
      changeCheckCode(0)
      return;
    }
    if (opType.value==0){
      proxy.Message.success("注册成功")
      showPanel(1)
    }else if (opType.value==1){
      if (params.remenberMe){
        const loginInfo = {
          email:params.email,
          password:params.password,
          remenberMe: params.remenberMe
        };
        proxy.Cookies.set("loginInfo",loginInfo,"7d");
      }else {
        proxy.Cookies.remove("loginInfo");
      }
      proxy.Message.success("登录成功");
      //存储cookie
      proxy.Cookies.set("userInfo",result.data,0)
      //重定向到原始页面
      const redirectUrl = route.query.redirectUrl||"/home";
      router.push(redirectUrl);
    }else if(opType.value==2){
      proxy.Message.success("重置成功")
      showPanel(1)
    }
  })
}
onMounted(()=>{
  showPanel(1)
})
//重置表单
const restForm=()=>{
  changeCheckCode(0);
  formDataRef.value.resetFields();
  formData.value = {}
  if (opType.value==1){
    let cookieLoginInfo = proxy.Cookies.get("loginInfo");
    if (cookieLoginInfo){
      formData.value = cookieLoginInfo;
    }
  }
}
</script>

<style scoped>
.login-body{
  height: calc(100vh);
  background-size: cover;
  background: url("../assets/login_bg.jpg");
  display: flex;
  .bg{
    flex: 1;
    background-size: cover;
    background-position: center;
    background-size: 800px;
    background-repeat: no-repeat;
    background-image: url("../assets/bg(1).png");
  }
  .login-panel{
    width: 430px;
    margin-right:15%;
    margin-top: calc( (100vh - 500px)/2);
    .login-title{
      text-align: center;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .login-register{
      padding: 25px;
      background: #fff;
      border-radius: 5px;
    }
    .login-btn-qq {
      display: flex;
      margin-top: 20px;
      text-align: center;
      align-items: center;
      justify-content: center;
      .img {
        cursor: pointer;
        width: 20px;
        margin-left: 5px;
      }
    }
  }
  .check-code-panel{
    width: 100%;
    display: flex;
    .check-code{
      margin-left: 5px;
      cursor: pointer;
    }
  }
  .remenberme-panel{
    width: 100%;
  }
  .no-account{
    width: 100%;
    display: flex;
    justify-content: space-between;   /*左右分布*/
  }
  .op-btn{
    width: 100%;
  }
  .send-email-panel{
    display: flex;
    width: 100%;
    justify-content: space-between;
    .send-mail-btn {
      margin-left: 5px;
    }
  }

}
</style>